const express = require('express');
const http = require('http');
const cors = require('cors');
const mongoose = require('mongoose');
const webSocketService = require('./services/websocket.service');
require('dotenv').config();

const projectRoutes = require('./routes/project.routes');
const deployRoutes = require('./routes/deploy.routes');
const authRoutes = require('./routes/auth.routes');
const settingsRoutes = require('./routes/settings.routes');
const { auth } = require('./middleware/auth.middleware');

const app = express();
const server = http.createServer(app);

// 初始化WebSocket服务
webSocketService.initialize(server);

app.use(cors());
app.use(express.json());

// 连接数据库
mongoose.connect(process.env.MONGODB_URI, {
  useNewUrlParser: true,
  useUnifiedTopology: true
}).then(() => {
  console.log('Connected to MongoDB:', process.env.MONGODB_URI);
}).catch((error) => {
  console.error('MongoDB connection error:', error);
  process.exit(1); // 如果数据库连接失败，终止应用
});

// 监听数据库连接事件
mongoose.connection.on('error', err => {
  console.error('MongoDB connection error:', err);
});

mongoose.connection.on('disconnected', () => {
  console.warn('MongoDB disconnected. Attempting to reconnect...');
});

mongoose.connection.on('reconnected', () => {
  console.log('MongoDB reconnected');
});

// 路由注册
app.use('/api/auth', authRoutes);
app.use('/api/settings', auth, settingsRoutes);
app.use('/api/projects', auth, projectRoutes);
app.use('/api/deploy', auth, deployRoutes);

// 添加静态文件服务
app.use('/uploads', express.static('uploads'));

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error('Error:', err);
  res.status(500).json({ 
    error: '服务器内部错误',
    message: err.message,
    stack: process.env.NODE_ENV === 'development' ? err.stack : undefined
  });
});

const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

// 处理未捕获的异常
process.on('unhandledRejection', (err) => {
  console.error('Unhandled Promise Rejection:', err);
});

process.on('uncaughtException', (err) => {
  console.error('Uncaught Exception:', err);
  process.exit(1);
}); 